﻿using System;
using Model;
using System.Web.UI.WebControls;
using BusinessObject;
using System.Web.UI;

namespace ViewLayer.Pages.Historys
{
    public partial class InicioHistory : System.Web.UI.Page
    {
        User user;
        Project project;

        protected void Page_Load(object sender, EventArgs e)
        {
            user = (User)Session["User"];

            if (user == null)
            {
                Response.Redirect("../Account/Login.aspx");
            }
            if (!IsPostBack)
            {
                this.populateDdlSprint(this.ddlSprint);
                this.populateHistory();
            }
        }

        protected void lnkbCadastro_Click(object sender, EventArgs e)
        {
            Response.Redirect("../Historys/CadastroHistory.aspx");
        }

        protected void lnkbImportHistory_Click(object sender, EventArgs e)
        {
            Response.Redirect("../Historys/Importacao.aspx");
        }

        private void populateDdlEpic(DropDownList ddList)
        {
            ddList.DataSource = EpicBO.Instance.GetEpicByProject(Session["Project"] as Project);
            ddList.DataTextField = "Nome";
            ddList.DataValueField = "Id";
            ddList.DataBind();
            ddList.Items.Add(new ListItem("Sem Associação", "0"));

            ddList.SelectedValue = "0";
        }

        private void populateDdlSprint(DropDownList ddList)
        {
            ddList.DataSource = SprintBO.Instance.GetSprintByProject(Session["Project"] as Project);
            ddList.DataTextField = "Nome";
            ddList.DataValueField = "Id";
            ddList.DataBind();
            ddList.Items.Add(new ListItem("Sem Associação", "0"));

            ddList.SelectedValue = "0";
        }

        protected void ddlSprint_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.populateHistory();
        }

        private void populateHistory()
        {
            //consulta todos sprints do projeto.
            if (int.Parse(this.ddlSprint.SelectedValue) == 0)
            {
                this.grdHistorys.DataSource = HistoryBO.Instance.GetHistoryByProject(Session["Project"] as Project);
            }
            else
            {
                this.grdHistorys.DataSource = HistoryBO.Instance.GetHistoryBySprint(SprintBO.Instance.GetById(int.Parse(this.ddlSprint.SelectedValue)));
            }

            this.grdHistorys.DataBind();
        }

        protected void grdHistorys_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                History history = e.Row.DataItem as History;

                //exibição
                (e.Row.FindControl("lblNomeHistory") as Label).Text = history.Nome;
                (e.Row.FindControl("lblDescHistory") as Label).Text = history.Descricao;
                (e.Row.FindControl("lblMelhorCaso") as Label).Text = history.MelhorCaso.ToString();
                (e.Row.FindControl("lblCasoMedio") as Label).Text = history.CasoMedio.ToString();
                (e.Row.FindControl("lblPiorCaso") as Label).Text = history.PiorCaso.ToString();
                (e.Row.FindControl("btnAtualizar") as Button).CommandArgument = history.Id.ToString();

                //edição
                (e.Row.FindControl("txtNomeHistory") as TextBox).Text = history.Nome;
                (e.Row.FindControl("txtDescHistory") as TextBox).Text = history.Descricao;
                (e.Row.FindControl("txtMelhorCaso") as TextBox).Text = history.MelhorCaso.ToString();
                (e.Row.FindControl("txtCasoMedio") as TextBox).Text = history.CasoMedio.ToString();
                (e.Row.FindControl("txtPiorCaso") as TextBox).Text = history.PiorCaso.ToString();

                (e.Row.FindControl("btnSalvar") as Button).CommandArgument = history.Id.ToString();

                DropDownList ddlSprintsToAssociate = e.Row.FindControl("ddlSprintToAssociate") as DropDownList;
                DropDownList ddlEpicToAssociate = e.Row.FindControl("ddlEpicToAssociate") as DropDownList;

                this.populateDdlSprint(ddlSprintsToAssociate);
                this.populateDdlEpic(ddlEpicToAssociate);

                //atualiza o valor do sprint associado a history
                if (history.Sprint != null)
                {
                    ddlSprintsToAssociate.SelectedIndex = history.Sprint.Id;
                    (e.Row.FindControl("lblSprintAssociate") as Label).Text = history.Sprint.Nome;
                }
                if (history.Epic != null)
                {
                    ddlEpicToAssociate.SelectedIndex = history.Epic.Id;
                    (e.Row.FindControl("lblEpicAssociate") as Label).Text = history.Epic.Nome;
                }
            }
        }

        protected void grdHistorys_RowCommand(object sender, GridViewCommandEventArgs e)
        {          
            if (e.CommandName.ToLower() == "editar")
            {
                GridViewRow grd = (GridViewRow)((Control)e.CommandSource).NamingContainer;
                ControlsVisibilityManager(grd, true);
            }

            if (e.CommandName.ToLower() == "salvar")
            {
                GridViewRow grd = (GridViewRow)((Control)e.CommandSource).NamingContainer;

                History history = HistoryBO.Instance.GetById(Convert.ToInt32(e.CommandArgument));

                history.Nome = (grd.FindControl("txtNomeHistory") as TextBox).Text;
                history.Descricao = (grd.FindControl("txtDescHistory") as TextBox).Text;
                history.MelhorCaso = Convert.ToDouble((grd.FindControl("txtMelhorCaso") as TextBox).Text);
                history.CasoMedio = Convert.ToDouble((grd.FindControl("txtCasoMedio") as TextBox).Text);
                history.PiorCaso = Convert.ToDouble((grd.FindControl("txtPiorCaso") as TextBox).Text);

                var sprIndex = Convert.ToInt32((grd.FindControl("ddlSprintToAssociate") as DropDownList).SelectedValue);
                var epicIndex = Convert.ToInt32((grd.FindControl("ddlEpicToAssociate") as DropDownList).SelectedValue);

                //sprint to associate
                if (sprIndex > 0)
                {
                    history.Sprint = SprintBO.Instance.GetById(sprIndex);
                }
                else
                {
                    history.Sprint = null;
                }
                //sprint to associate
                if (epicIndex > 0)
                {
                    history.Epic = EpicBO.Instance.GetById(epicIndex);
                }
                else
                {
                    history.Epic = null;
                }

                HistoryBO.Instance.Update(history);

                populateHistory();
                ControlsVisibilityManager(grd, false);
            }
        }

        protected void grdHistorys_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grdHistorys.PageIndex = e.NewPageIndex;
            this.populateHistory();
        }

        /// <summary>
        /// Gerencia os controles dos campos na página.
        /// </summary>
        /// <param name="grd"></param>
        /// <param name="editar"></param>
        private static void ControlsVisibilityManager(GridViewRow grd, bool editar)
        {
            (grd.FindControl("txtNomeHistory") as TextBox).Visible = editar;
            (grd.FindControl("txtDescHistory") as TextBox).Visible = editar;
            (grd.FindControl("txtMelhorCaso") as TextBox).Visible = editar;
            (grd.FindControl("txtCasoMedio") as TextBox).Visible = editar;
            (grd.FindControl("txtPiorCaso") as TextBox).Visible = editar;
            (grd.FindControl("btnSalvar") as Button).Visible = editar;
            (grd.FindControl("ddlSprintToAssociate") as DropDownList).Visible = editar;
            (grd.FindControl("ddlEpicToAssociate") as DropDownList).Visible = editar;

            (grd.FindControl("lblNomeHistory") as Label).Visible = !editar;
            (grd.FindControl("lblDescHistory") as Label).Visible = !editar;
            (grd.FindControl("lblMelhorCaso") as Label).Visible = !editar;
            (grd.FindControl("lblCasoMedio") as Label).Visible = !editar;
            (grd.FindControl("lblPiorCaso") as Label).Visible = !editar;
            (grd.FindControl("btnAtualizar") as Button).Visible = !editar;
            (grd.FindControl("lblSprintAssociate") as Label).Visible = !editar;
            (grd.FindControl("lblEpicAssociate") as Label).Visible = !editar;
        }
    }
}